package com.bjor.beerdaddy;


import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;


import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;


@SuppressWarnings("deprecation")
public class MainController extends TabActivity {
	
	String TAG = getClass().getName();
	private float MENU_WIDTH = .8f;
	private static TabHost tabHost;
	ImageButton oneButton;
	ImageButton twoButton;
	ImageButton threeButton;
	ImageButton fourButton;
	ImageButton fiveButton;
	ImageButton exitButton;
	private RelativeLayout header;
	private RelativeLayout content;
	private RelativeLayout contentViewOverlay;
	private static TextView headerTitle;
	private MainControllerGestureEventListener gestureEventListenerHeaderView;
	private MainControllerGestureEventListener gestureEventListenerMenuButton;
	private GestureDetector gestureScannerHeaderView;
	private GestureDetector gestureScannerBackButton;
	static Map<String, String> mapActivityTitles;
	public static final String PREFS_NAME = "MyPrefsFile";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        tabHost = getTabHost();
        setup();
        addActivities();
	}
	
	private void addActivities() {
		createActivity(SettingsActivity.class, "Settings");
		createActivity(PickPlanActivity.class, "PickPlan");
//		createActivity(MainControllerForRelationActivity.class, "Eitthvad nr 3");
//		createActivity(AboutActivity.class, "Eitthvad nr 4");
//		createActivity(ActivityFive.class, "Eitthvad nr 5");
//		createActivity(BumpActivity.class, "Eitthvad nr 5");
//		createActivity(RelationActivity.class, "Eitthvad nr 5");
//		if(Global.getTraceId()==null)
//			tabHost.setCurrentTabByTag(SearchActivity.class.toString());
//		else
//			tabHost.setCurrentTabByTag(RelationActivity.class.toString());		
		tabHost.setCurrentTabByTag(SettingsActivity.class.toString());
		headerTitle.setText(mapActivityTitles.get(SettingsActivity.class.toString()));
	}
	
	private void createActivity(Class<?> cls, String title) {
		TabHost.TabSpec tabSpec;
        tabSpec = tabHost.newTabSpec(cls.toString());
        tabSpec.setIndicator("");
        tabSpec.setContent(new Intent(this, cls));
        tabHost.addTab(tabSpec);
        mapActivityTitles.put(cls.toString(), title);
	}
	
	private void setup() {
		header = (RelativeLayout)findViewById(R.id.header);
		content = (RelativeLayout)findViewById(R.id.tabLayout);
		contentViewOverlay = (RelativeLayout)findViewById(R.id.contentOverlay);
		headerTitle = (TextView)findViewById(R.id.headerTitle);
		mapActivityTitles = new HashMap<String, String>();
		createGestureEventListener();
		bindHeaderView();		
		bindBackButton();
		bindContentViewOverlayOnTouchWhenMenuOpened();
		//bindButtons();
		tabHost.setOnTabChangedListener(new OnTabChangeListener()
		{
		    @Override
		    public void onTabChanged(String className) {
		    	try{
		    		final View tabContent = tabHost.findViewById(android.R.id.tabcontent);
			    	if(tabContent!=null){
			    		Animation fadeIn = AnimationUtils.loadAnimation(getBaseContext(), android.R.anim.fade_in);
			    	    tabContent.startAnimation(fadeIn);
			    	    headerTitle.startAnimation(fadeIn);
			    	}
		    	}catch(Exception e){
		    		Log.d(TAG, "onTabChanged exception: "+e.toString());
		    	}
		    }
		});
	}
	
	private void createGestureEventListener() {
		gestureEventListenerHeaderView = new MainControllerGestureEventListener() {
			@Override
			public void onSwipeRight() {
				if(!isMenuOpened())
					openMenu();
			}
			@Override
			public void onSwipeLeft() {
				if(isMenuOpened())
					closeMenu();
			}
			@Override
			public void onSwipeTop() {}
			@Override
			public void onSwipeBottom() {}
			@Override
			public void tapUp() {}
			@Override
			public void onScroll(float fromX, float fromY, float toX, float toY, float movedInX, float movedInY) {}
		};
		gestureScannerHeaderView = new GestureDetector(getApplicationContext(), new HeaderGestureListener(gestureEventListenerHeaderView));
		gestureEventListenerMenuButton = new MainControllerGestureEventListener() {
			@Override
			public void onSwipeRight() {
				if(!isMenuOpened())
					openMenu();
			}
			@Override
			public void onSwipeLeft() {
				if(isMenuOpened())
					closeMenu();
			}
			@Override
			public void onSwipeTop() {}
			@Override
			public void onSwipeBottom() {}
			@Override
			public void tapUp() {
				if(isMenuOpened())
					closeMenu();
				else
					openMenu();
			}
			@Override
			public void onScroll(float fromX, float fromY, float toX, float toY, float movedInX, float movedInY) {}
		};
		gestureScannerBackButton = new GestureDetector(getApplicationContext(), new HeaderGestureListener(gestureEventListenerMenuButton));
	}
	
	private void bindHeaderView() {
		header.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return gestureScannerHeaderView.onTouchEvent(event);
			}
		});
	}
	
	private void manuallySetActivityLeftMargin(int left) {
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
        params = (RelativeLayout.LayoutParams)content.getLayoutParams();
        params.setMargins(left,0,(left*(-1)),0);
        content.setLayoutParams(params);
	}
	
	public boolean isMenuOpened() {
		return (((RelativeLayout.LayoutParams)content.getLayoutParams()).leftMargin==0) ? false:true;
	}
	
	private void bindBackButton() {
		ImageView menuButton = (ImageView)header.findViewById(R.id.menuButton);
		menuButton.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return gestureScannerBackButton.onTouchEvent(event);
			}
		});
	}
	
	private void bindContentViewOverlayOnTouchWhenMenuOpened() {
		contentViewOverlay.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(isMenuOpened()){
					closeMenu();
					return false;
				}else
					return true;
			}
		});
	}
	
	public void openMenu() {
		buttonsAvailable();
		contentViewOverlay.setVisibility(View.VISIBLE);
		Animation moveRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.view_to_right);
		moveRight.setAnimationListener(
	        new AnimationListener() {
	            @Override
	            public void onAnimationStart(Animation animation) {}
	            @Override
	            public void onAnimationRepeat(Animation animation) {}
	            @Override
	            public void onAnimationEnd(Animation animation) {
	            	content.clearAnimation();
	            	manuallySetActivityLeftMargin((int)(getWindowWidth()*MENU_WIDTH));
	            }
	        }
	    );
		content.startAnimation(moveRight);
	}
	
	public int getWindowWidth() {
		DisplayMetrics metrics = new DisplayMetrics();
    	getWindowManager().getDefaultDisplay().getMetrics(metrics);
    	return metrics.widthPixels;
	}
	
	public void closeMenu() {
		buttonsUnavailable();
		contentViewOverlay.setVisibility(View.GONE);
		Animation moveLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.view_to_left);
		manuallySetActivityLeftMargin(0);
		moveLeft.setAnimationListener(
		        new AnimationListener() {
		            @Override
		            public void onAnimationStart(Animation animation) {}
		            @Override
		            public void onAnimationRepeat(Animation animation) {}
		            @Override
		            public void onAnimationEnd(Animation animation) {
		            	content.clearAnimation();
		            }
		        }
		    );
		content.startAnimation(moveLeft);
	}
	
	/* private void bindButtons() {
		oneButton = (Button)findViewById(R.id.oneButton);
		twoButton = (Button)findViewById(R.id.twoButton);
		threeButton = (Button)findViewById(R.id.threeButton);
		fourButton = (Button)findViewById(R.id.fourButton);
		fiveButton = (Button)findViewById(R.id.fiveButton);
		exitButton = (Button)findViewById(R.id.logoutButton);
	} */
	
	private void buttonsAvailable() {
		oneButton = (ImageButton)findViewById(R.id.oneButton);
		twoButton = (ImageButton)findViewById(R.id.twoButton);
		threeButton = (ImageButton)findViewById(R.id.threeButton);
		fourButton = (ImageButton)findViewById(R.id.fourButton);
		fiveButton = (ImageButton)findViewById(R.id.fiveButton);
//		exitButton = (ImageButton)findViewById(R.id.logoutButton);
		
		oneButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			     oneButton.setImageResource(R.drawable.quickstart_selected);
			     twoButton.setImageResource(R.drawable.createplan);
			     threeButton.setImageResource(R.drawable.myhistory);
			     fourButton.setImageResource(R.drawable.settings);
			     fiveButton.setImageResource(R.drawable.faq);
//			     exitButton.setImageResource(R.drawable.utskraicon);
			     //closeMenuAndStartIntent(SettingsActivity.class.toString());
			}
		});
		twoButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 oneButton.setImageResource(R.drawable.quickstart);
			     twoButton.setImageResource(R.drawable.createplan_selected);
			     threeButton.setImageResource(R.drawable.myhistory);
			     fourButton.setImageResource(R.drawable.settings);
			     fiveButton.setImageResource(R.drawable.faq);
//			     exitButton.setImageResource(R.drawable.utskraicon);
				 closeMenuAndStartIntent(PickPlanActivity.class.toString());
			}
		});
		threeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			     oneButton.setImageResource(R.drawable.quickstart);
			     twoButton.setImageResource(R.drawable.createplan);
			     threeButton.setImageResource(R.drawable.myhistory_selected);
			     fourButton.setImageResource(R.drawable.settings);
			     fiveButton.setImageResource(R.drawable.faq);
//			     exitButton.setImageResource(R.drawable.utskraicon);
				//closeMenuAndStartIntent(FacebookActivity.class.toString());
			}
		});
		
		fourButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 oneButton.setImageResource(R.drawable.quickstart);
			     twoButton.setImageResource(R.drawable.createplan);
			     threeButton.setImageResource(R.drawable.myhistory);
			     fourButton.setImageResource(R.drawable.settings_selected);
			     fiveButton.setImageResource(R.drawable.faq);
//			     exitButton.setImageResource(R.drawable.utskraicon);
				 closeMenuAndStartIntent(SettingsActivity.class.toString());
			}
		});
		
		fiveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 oneButton.setImageResource(R.drawable.quickstart);
			     twoButton.setImageResource(R.drawable.createplan);
			     threeButton.setImageResource(R.drawable.myhistory);
			     fourButton.setImageResource(R.drawable.settings);
			     fiveButton.setImageResource(R.drawable.faq_selected);
//			     exitButton.setImageResource(R.drawable.utskraicon);
				 //closeMenuAndStartIntent(BumpActivity.class.toString());
			}
		});
/*		exitButton.setOnClickListener(new OnClickListener() {
			@Override
			
			
			
			
			public void onClick(View v) {
			    oneButton.setImageResource(R.drawable.leiticon);
			    twoButton.setImageResource(R.drawable.ummigicon);
			    threeButton.setImageResource(R.drawable.fbicon);
			    fourButton.setImageResource(R.drawable.umappicon);
			    fiveButton.setImageResource(R.drawable.bumpicon);
			    exitButton.setImageResource(R.drawable.utskraiconvalid);				
			    SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
		        editor.putBoolean("logedIn", false);
				editor.putString("username", null);
		        editor.putString("password", null);
		        editor.commit();
		        Global.clearAll();
		        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
		    	startActivity(intent);
				finish();
			}
		}); */

	}
	
	private void buttonsUnavailable() {
		oneButton = (ImageButton)findViewById(R.id.oneButton);
		twoButton = (ImageButton)findViewById(R.id.twoButton);
		threeButton = (ImageButton)findViewById(R.id.threeButton);
		fourButton = (ImageButton)findViewById(R.id.fourButton);
		fiveButton = (ImageButton)findViewById(R.id.fiveButton);
//		exitButton = (ImageButton)findViewById(R.id.logoutButton);
		
		oneButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		twoButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		threeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		fourButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		fiveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		/*exitButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});*/
	}
	
	private void startIntent(final String tag) {
		Log.e("TAG", tag);
		final View tabContent = tabHost.findViewById(android.R.id.tabcontent);
    	if( tabContent != null ){
    		Animation fadeOut = AnimationUtils.loadAnimation(getBaseContext(), android.R.anim.fade_out);
   			tabContent.startAnimation(fadeOut);
   			headerTitle.startAnimation(fadeOut);
    	}
    	String k = "NULL";
		if (tabContent != null) k = "OK";
    	Log.e("content", k);
    	tabHost.setCurrentTabByTag(tag);
    	headerTitle.setText(mapActivityTitles.get(tag));
	}
	
	public static void outsideIntent(final String tag) {
		Log.e("TAG", tag);
		final View tabContent = tabHost.findViewById(android.R.id.tabcontent);
		String k = "NULL";
		if (tabContent != null) k = "OK";
    	Log.e("content", k);
    	tabHost.setCurrentTabByTag(tag);
    	headerTitle.setText(mapActivityTitles.get(tag));
	}
	
	void closeMenuAndStartIntent(String tag) {
		closeMenu();
		if(!tabHost.getCurrentTabTag().equals(tag))
			startIntent(tag);
	}
	
	@Override
	public void onBackPressed() {
		if(isMenuOpened())
			closeMenu();
		else
			super.onBackPressed();
	}
	
	
	
	
	
	
	
	
	
	
	/* private IBumpAPI api;

	    private final ServiceConnection connection = new ServiceConnection() {
	        @Override
	        public void onServiceConnected(ComponentName className, IBinder binder) {
	            Log.i("BumpTest", "onServiceConnected");
	            api = IBumpAPI.Stub.asInterface(binder);
	            new Thread() {
	                public void run() {
	                    try {
	                        api.configure("1d1aea4324414fdca96f5e455d071323",
	                                "Bump User");
	                    } catch (RemoteException e) {
	                        Log.w("BumpTest", e);
	                    }

	                }
	            }.start();
	            Log.d("Bump Test", "Service connected");
	        }

	        @Override
	        public void onServiceDisconnected(ComponentName className) {
	            Log.d("Bump Test", "Service disconnected");
	        }
	    };
	    
	    public void onSuccess(String response){
	    	try {
				api.disableBumping();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            Global.setTraceId(response.trim());
            Log.i("Valdi", "Fengid id: " + response);
            Log.i("Valdi", "Fengid id trim: " + response.trim());
            Intent intent = new Intent(getApplicationContext(), MainController.class);
        	startActivityForResult(intent, 0);
	    }

	    private final BroadcastReceiver receiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            final String action = intent.getAction();
	            try {
	            	String messageReceived = "";
                    String messageToSend = Global.getSessionid();
	                if (action.equals(BumpAPIIntents.DATA_RECEIVED)) 
	                {
	                    Log.i("Bump Test", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0))); 
	                    messageReceived = new String(intent.getByteArrayExtra("data"));
	                    WhoisTask whoisTask = new WhoisTask(MainController.this);
	            		whoisTask.execute(messageReceived);
	                } 
	                else if (action.equals(BumpAPIIntents.MATCHED)) 
	                {
	                    long channelID = intent.getLongExtra("proposedChannelID", 0); 
	                    Log.i("Bump Test", "Matched with: " + api.userIDForChannelID(channelID));
	                    api.confirm(channelID, true);
	                    Log.i("Bump Test", "Confirm sent");
	                } 
	                else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) 
	                {
	                    long channelID = intent.getLongExtra("channelID", 0);
	                    Log.i("Bump Test", "Channel confirmed with " + api.userIDForChannelID(channelID));
	                    api.send(channelID, messageToSend.getBytes());
	                } 
	                else if (action.equals(BumpAPIIntents.NOT_MATCHED)) 
	                {
	                    Log.i("Bump Test", "Not matched.");
	                    Toast.makeText(getApplicationContext(), getString(R.string.not_matched), Toast.LENGTH_SHORT).show();
	                } 
	                else if (action.equals(BumpAPIIntents.CONNECTED))
	                {
	                    Log.i("Bump Test", "Connected to Bump...");
	                    api.enableBumping();
	                }
	            } 
	            catch (RemoteException e) {}
	        } 
	    };

	    @Override
	    public void onConfigurationChanged(Configuration newConfig) {
	      super.onConfigurationChanged(newConfig);
	    }


	    public void initializeTheBump()
	    {
	        bindService(new Intent(IBumpAPI.class.getName()),
	                    connection, Context.BIND_AUTO_CREATE);
	        Log.i("BumpTest", "boot");

	        IntentFilter filter = new IntentFilter();
	        filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
	        filter.addAction(BumpAPIIntents.DATA_RECEIVED);
	        filter.addAction(BumpAPIIntents.NOT_MATCHED);
	        filter.addAction(BumpAPIIntents.MATCHED);
	        filter.addAction(BumpAPIIntents.CONNECTED);
	        registerReceiver(receiver, filter);
	    }

	     public void onStart() {
	        Log.i("BumpTest", "onStart");
	        super.onStart();
	     }
	     
	     public void onRestart() {
	        Log.i("BumpTest", "onRestart");
	        super.onRestart();
	     }

	     public void onResume() {
	        Log.i("BumpTest", "onResume");
	        super.onResume();
	     }

	     public void onPause() {
	        Log.i("BumpTest", "onPause");
	        super.onPause();
	     }

	     public void onStop() {
	        Log.i("BumpTest", "onStop");
	        super.onStop();
	     }

	     public void onDestroy() {
	        Log.i("BumpTest", "onDestroy");
//	        unbindService(connection);
//	        Log.i("unbind", "unbinding done");
//	        unregisterReceiver(receiver);
//	        Log.i("unregister", "unregistering done");
	        super.onDestroy();
	     } */
}